import Vue from 'vue';
import axios from 'axios';
import router from '../router/index';
// import store from "@/store";
const http = axios.create({
    baseURL: 'http://124.223.199.129:8080',
    timeout: 1000 * 30,
    // withCredentials: true,
    headers: {
        'Content-Type': 'application/json; charset=utf-8',
    },
});

/**
 * 请求拦截
 */
http.interceptors.request.use(
    (config) => {
        console.log('发送请求');
        // config.headers['token'] = Vue.cookie.get('token');
        return config;
    },
    (error) => {
        console.log('请求失败！！');
        console.log(error);
        // Vue.prototype.$message.error('请求超时');
        return Promise.reject(error);
    }
);

/**
 * 响应拦截
 */
http.interceptors.response.use(
    (response) => {
        // const res = response.data;
        console.log(response);
        return response;
    },
    (error) => {
        console.log(error);
        if (error.response) {
            switch (error.response.status) {
                case 401:
                    // Vue.cookie.delete('token');
                    router.replace({
                        name: 'login',
                    });
            }
        }
        return Promise.reject(error.response);
    }
);
/**
 * get方法，对应get请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function get(url, params) {
    return new Promise((resolve, reject) => {
        http.get(url, {
            params: params,
        })
            .then((res) => {
                resolve(res.data);
            })
            .catch((err) => {
                reject(err.data);
            });
    });
}
/**
 * post方法，对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function post(url, params) {
    return new Promise((resolve, reject) => {
        http.post(url, params)
            .then((res) => {
                resolve(res.data);
            })
            .catch((err) => {
                reject(err);
            });
    });
}
/**
 * put方法，对应put请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function put(url, params) {
    return new Promise((resolve, reject) => {
        http.put(url, params)
            .then((res) => {
                resolve(res.data);
            })
            .catch((err) => {
                reject(err.data);
            });
    });
}
/**
 * del 方法，对应del 请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function del(url, params) {
    return new Promise((resolve, reject) => {
        http.delete(url, { params: params })
            .then((res) => {
                resolve(res.data);
            })
            .catch((err) => {
                reject(err.data);
            });
    });
}

//导出
export default http;
